package com.miplus.ccrm.core.service.strategy;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.github.yulichang.interfaces.MPJBaseJoin;
import com.github.yulichang.query.MPJLambdaQueryWrapper;
import com.github.yulichang.query.MPJQueryWrapper;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.miplus.ccrm.common.CmdResVo;
import com.miplus.ccrm.common.ServiceException;
import com.miplus.ccrm.core.controller.vo.LabelResVo;
import com.miplus.ccrm.core.controller.vo.strategy.*;
import com.miplus.ccrm.core.pojo.*;
import com.miplus.ccrm.core.service.aiqm.QmDataService;
import com.miplus.ccrm.core.service.crd.FiCreditcasesService;
import com.miplus.ccrm.core.service.crd.FiTaskService;
import com.miplus.ccrm.core.service.cust.ConCustomerService;
import com.miplus.ccrm.core.service.strategy.CfgRuleTaskStepsService;
import com.miplus.ccrm.core.mapper.CfgRuleTaskStepsMapper;
import com.miplus.ccrm.core.utils.EnumRuleStepAction;
import com.miplus.ccrm.core.utils.EnumRuleVarsOp;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.sql.SQLException;
import java.util.*;

import java.util.List;

/**
* @author wangzl
* @description 针对表【cfg_rule_task_steps】的数据库操作Service实现
* @createDate 2024-10-22 10:35:02
*/
@Slf4j
@Service
public class CfgRuleTaskStepsServiceImpl extends MPJBaseServiceImpl<CfgRuleTaskStepsMapper, CfgRuleTaskSteps>
    implements CfgRuleTaskStepsService{

    @Resource
    private CfgRuleVarsService cfgRuleVarsService;
    @Resource
    private CfgRuleConditionsService cfgRuleConditionsService;
    @Resource
    private CfgActivityService cfgActivityService;
    @Resource
    private CfgAssignsetService cfgAssignsetService;

    @Resource
    private ConCustomerService conCustomerService;

    @Resource
    private FiCreditcasesService fiCreditcasesService;

    @Resource
    private CfgActivityOthergrplinkService cfgActivityOthergrplinkService;

    @Resource
    private FiTaskService fiTaskService;

    @Resource
    private QmDataService qmDataService;

    @Override
    public IPage<RuleStepListResVo> getRuleStepList(String usrId, RuleStepListReqVo ruleStepListReqVo)
    {
        return selectJoinListPage( new Page<>(ruleStepListReqVo.getPageNum(),ruleStepListReqVo.getPageSize()),
                RuleStepListResVo.class,
                new MPJLambdaWrapper<CfgRuleTaskSteps>()
                        .leftJoin(CfgActivity.class,"ca",CfgActivity::getActivityid,CfgRuleTaskSteps::getActivityId)
                        .leftJoin(CpCalllist.class,"cl",CpCalllist::getClid, CfgRuleTaskSteps::getClid)
                        .leftJoin(CfgAssignset.class,"cas", CfgAssignset::getAssignId,CfgRuleTaskSteps::getAssignId)
                        .leftJoin("sys_grp sg on sg.grpid = cas.grpid")
                        .selectAs("fun_getnames('RULE.STEP.ACTIONCODE',t.action_code)",RuleStepListResVo::getActionCodeDesc)
                        .selectAs("fun_getnames('RULE.STEP.FILTERTYPE',t.filter_type)",RuleStepListResVo::getFilterTypeDesc)
                        .selectAs("sg.grpname",RuleStepListResVo::getGrpName)
                        .selectAs("cl.name",RuleStepListResVo::getClName)
                        .selectAs("cl.channel", RuleStepListResVo::getChannel)
                        .selectAs("fun_getnames('CAMPAIGN.CHANNEL',cl.channel)",RuleStepListResVo::getChannelDesc)
                        .selectAll(CfgRuleTaskSteps.class)
                        .eq(ObjectUtils.isNotNull(ruleStepListReqVo.getStepId()),CfgRuleTaskSteps::getRuleStepId,ruleStepListReqVo.getStepId())
                        .eq(ObjectUtils.isNotNull(ruleStepListReqVo.getStatus()),CfgRuleTaskSteps::getStatus,ruleStepListReqVo.getStatus())
                        .in(ObjectUtils.isNotNull(ruleStepListReqVo.getActionCode()),CfgRuleTaskSteps::getActionCode,ruleStepListReqVo.getActionCode())
                        .in(ObjectUtils.isNotNull(ruleStepListReqVo.getChannel()),CpCalllist::getChannel,ruleStepListReqVo.getChannel())
                        .like(StringUtils.isNotEmpty(ruleStepListReqVo.getStepName()),CfgRuleTaskSteps::getRuleStepName,ruleStepListReqVo.getStepName())
                        .ge(StringUtils.isNotEmpty(ruleStepListReqVo.getStartDate()),CfgRuleTaskSteps::getCrdt,ruleStepListReqVo.getStartDate())
                        .le(StringUtils.isNotEmpty(ruleStepListReqVo.getEndDate()),CfgRuleTaskSteps::getCrdt,ruleStepListReqVo.getEndDate())
                        .notExists(ObjectUtils.isNotNull(ruleStepListReqVo.getExcludeTaskId()),"select 1 from cfg_rule_task_step_link csl where csl.rule_step_id=t.rule_step_id and csl.rule_task_id=" + ruleStepListReqVo.getExcludeTaskId())
                );
    }

    @Override
    public List<LabelResVo> getRuleStepSelectList(Integer actionCode) {
        return selectJoinList(LabelResVo.class,new MPJLambdaWrapper<>(CfgRuleTaskSteps.class)
                .selectAs("CONCAT(rule_step_name,'(ID:',rule_step_id,')')",LabelResVo::getLabel)
                .selectAs(CfgRuleTaskSteps::getRuleStepId,LabelResVo::getValue)
                .eq(CfgRuleTaskSteps::getActionCode,actionCode)
        );
    }

    @Override
    public RuleStepResVo getRuleStepInfo(Long ruleStepId)
    {
        RuleStepResVo ruleStepResVo = new RuleStepResVo();
        ruleStepResVo = selectJoinOne(
                RuleStepResVo.class,
                new MPJLambdaWrapper<CfgRuleTaskSteps>()
                      //  .leftJoin(CfgActivity.class,"ca",CfgActivity::getActivityid,CfgRuleTaskSteps::getActivityId)
                        .leftJoin(CpCalllist.class,"cl",CpCalllist::getClid, CfgRuleTaskSteps::getClid)
                        .leftJoin(CfgAssignset.class,"cs", CfgAssignset::getAssignId,CfgRuleTaskSteps::getAssignId)
                        .selectAs("fun_getnames('RULE.STEP.ACTIONCODE',t.action_code)",RuleStepResVo::getActionCodeDesc)
                        .selectAs("fun_getnames('RULE.STEP.FILTERTYPE',t.filter_type)",RuleStepResVo::getFilterTypeDesc)
                        .selectAs("cl.name",RuleStepResVo::getClname)
                        .selectAll(CfgRuleTaskSteps.class)
                        .eq(CfgRuleTaskSteps::getRuleStepId,ruleStepId)
        );
        if(ruleStepResVo == null)
            return null;
        if( ruleStepResVo.getActionCode().equals(EnumRuleStepAction.DISTRIBUTE.getCode())) {
            ActivityEditVo activityEditVo = new ActivityEditVo();
            BeanUtils.copyProperties(cfgActivityService.getById(ruleStepResVo.getActivityId()), activityEditVo);
            activityEditVo.setOutgrplist(cfgActivityOthergrplinkService.getActivityList(ruleStepResVo.getActivityId()));
            ruleStepResVo.setCfgActivity(activityEditVo);
        }
        if( ruleStepResVo.getActionCode().equals(EnumRuleStepAction.ASSIGN.getCode())) {
            AssSetResVo assSetResVo = new AssSetResVo();
            BeanUtils.copyProperties(cfgAssignsetService.getById(ruleStepResVo.getAssignId()),assSetResVo);
            assSetResVo.setAssUsrList(cfgAssignsetService.assignRatioList(assSetResVo.getGrpid(),ruleStepResVo.getAssignId()));
            ruleStepResVo.setCfgAssignset(assSetResVo);
        }
        ruleStepResVo.setCfgRuleConditionsList(getRuleConditionList(ruleStepId));
        return ruleStepResVo;
    }

    /**
     * 获取条件列表
     */
    @Override
    public List<CfgRuleConditions> getRuleConditionList(Long ruleStepId)
    {
        return cfgRuleConditionsService.getBaseMapper().selectList(
                new LambdaQueryWrapper<CfgRuleConditions>().eq(CfgRuleConditions::getRuleStepId,ruleStepId));
    }

    @Override
    @Transactional
    public CmdResVo addRuleStep(String usrId, RuleStepReqVo vo)
    {
        if(ObjectUtils.isNull(vo.getActionCode()))
            throw  new ServiceException(1001,"动作不能为空");
//        DISTRIBUTE(1, "分案"),
//                ASSIGN(2, "派工"),
//                CAMPAIGN(3, "活动"),
//                CALLBACK(4, "退回案件池"),
//                GRPCALLBACK(5,"部门回收"),
//                ADDCUSTTAG(6,"添加客户分组标签"),
//                DELETECUSTTAG(7,"删除客户分组标签"),
//                ADDCOLLECTTAG(8,"添加催案分组标签"),
//                DELETECOLLECTTAG(9,"删除催案分组标签");
        CfgRuleTaskSteps cfgRuleTaskSteps = new CfgRuleTaskSteps();
        BeanUtils.copyProperties(vo, cfgRuleTaskSteps);
        EnumRuleStepAction stepAction = EnumRuleStepAction.getEnumByCode(vo.getActionCode());
        if(stepAction == null )
            throw  new ServiceException(1001,"动作不能为空");
        if( (stepAction == EnumRuleStepAction.ADDCUSTTAG
            || stepAction == EnumRuleStepAction.DELETECUSTTAG
            || stepAction == EnumRuleStepAction.ADDCOLLECTTAG
            || stepAction == EnumRuleStepAction.DELETECOLLECTTAG)
            && StringUtils.isEmpty(vo.getTag()))
        {
            throw new ServiceException(1001, "标签不能空");
        }
        if( stepAction == EnumRuleStepAction.CAMPAIGN && StringUtils.isEmpty(vo.getClid()))
        {
            throw new ServiceException(1001, "任务队列不能为空");
        }
        if( stepAction == EnumRuleStepAction.DISTRIBUTE)
        {
             if( vo.getCfgActivity() == null)
                 throw new ServiceException(1001, "未定义分案信息");
            ActivityEditVo cfgActivity = vo.getCfgActivity();
           // ActivityEditVo cfgActivity = new CfgActivity();
           // BeanUtils.copyProperties(vo.getCfgActivity(),cfgActivity);
            if(ObjectUtils.isNull(cfgActivity.getDistype2() ))
                throw new ServiceException(1001, "未指定分案的分配方法");
            if(StringUtils.isEmpty(cfgActivity.getDistdaymode()))
                cfgActivity.setDistdaymode("0");
            if( cfgActivity.getDistdaymode().equals("0")
            && ObjectUtils.isNull(cfgActivity.getBindday()))
                throw new ServiceException(1001, "未指定绑定天数");
            if( cfgActivity.getDistdaymode().equals("1")
            && StringUtils.isEmpty(cfgActivity.getFixday()))
                throw new ServiceException(1001, "未指定到期日期");
//            cfgActivity.setCrdt(new Date());
//            cfgActivity.setCrusr(usrId);
//            cfgActivity.setName(vo.getStepName());

           CmdResVo cmdResVo = cfgActivityService.cfgActivityInsert(usrId, vo.getCfgActivity());
           cfgRuleTaskSteps.setActivityId( Integer.parseInt(cmdResVo.getKeyId()));
        }
        if( stepAction == EnumRuleStepAction.ASSIGN)
        {
            if( vo.getCfgAssignset() == null)
                throw new ServiceException(1001, "未定义派工信息");
            AssSetEditVo cfgAssignset = vo.getCfgAssignset();
//            CfgAssignset cfgAssignset = new CfgAssignset();
            BeanUtils.copyProperties(vo.getCfgAssignset(),cfgAssignset);
            if(ObjectUtils.isNull(cfgAssignset.getMode()))
                throw new ServiceException(1001, "未指定派工方法");
            if(StringUtils.isEmpty(cfgAssignset.getGrpid()))
                throw new ServiceException(1001, "未指定派工部门");
//            cfgAssignset.setMddt(new Date());
//            cfgAssignset.setMdusr(usrId);
//            cfgAssignsetService.save(cfgAssignset);
            CmdResVo cmdResVo =cfgAssignsetService.assignSetInsert(usrId, vo.getCfgAssignset());
            cfgRuleTaskSteps.setAssignId(Long.parseLong(cmdResVo.getKeyId()));
        }

        cfgRuleTaskSteps.setCrdt(new Date());
        cfgRuleTaskSteps.setCrusr(usrId);
        //更新分配表。

        save(cfgRuleTaskSteps);
        //if( vo.get)
        insertRuleStepConditions(usrId, cfgRuleTaskSteps.getRuleStepId(),vo.getCfgRuleConditionsList());
        //根据条件自动拼接SQL语句
        if( ObjectUtils.isNull(cfgRuleTaskSteps.getFilterType()) || cfgRuleTaskSteps.getFilterType() == 1) {
            cfgRuleTaskSteps.setFilterSql(
                    getStepConditionSql(cfgRuleTaskSteps.getRuleStepId(), cfgRuleTaskSteps.getFilterFormula()));
            updateById(cfgRuleTaskSteps);
        }
        return new CmdResVo(1,cfgRuleTaskSteps.getRuleStepId().toString());
    }
    /**
     *  更新策略条件表
     */

    private void insertRuleStepConditions(String usrId, Long ruleStepId, List<CfgRuleConditions> conditionList)
    {

        cfgRuleConditionsService.remove(new LambdaQueryWrapper<CfgRuleConditions>()
                .eq(CfgRuleConditions::getRuleStepId,ruleStepId));
        if( conditionList == null || conditionList.size() == 0)
            return;
        for(CfgRuleConditions cfgRuleConditions : conditionList)
        {
            addRuleCondition(usrId, ruleStepId, cfgRuleConditions);
        }
    }
    @Override
    public CmdResVo updateRuleStep(String usrId, RuleStepReqVo vo )
    {
        if(ObjectUtils.isNull(vo.getRuleStepId()) )
            throw  new ServiceException(1001,"策略ID不能为空");
        CfgRuleTaskSteps cfgRuleTaskSteps = getById(vo.getRuleStepId());
        if(cfgRuleTaskSteps == null){
            throw  new ServiceException(1001,"没有找到策略");
        }
        cfgRuleTaskSteps.setRuleStepName(vo.getRuleStepName());
        cfgRuleTaskSteps.setRuleStepDesc(vo.getRuleStepDesc());
        cfgRuleTaskSteps.setStatus(vo.getStatus());
        cfgRuleTaskSteps.setStartDate(vo.getStartDate());
        cfgRuleTaskSteps.setEndDate(vo.getEndDate());
        cfgRuleTaskSteps.setTag(vo.getTag());
        cfgRuleTaskSteps.setAddTagType(vo.getAddTagType());
        cfgRuleTaskSteps.setClid(vo.getClid());
        cfgRuleTaskSteps.setForceCallback(vo.getForceCallback());
        cfgRuleTaskSteps.setExcludeBlack(vo.getExcludeBlack());
        cfgRuleTaskSteps.setExcludeStop(vo.getExcludeStop());
        cfgRuleTaskSteps.setExcludeWhite(vo.getExcludeWhite());
        cfgRuleTaskSteps.setExcludeCustomerStop(vo.getExcludeCustomerStop());
        cfgRuleTaskSteps.setQmTemplateId(vo.getQmTemplateId());

        EnumRuleStepAction stepAction = EnumRuleStepAction.getEnumByCode(cfgRuleTaskSteps.getActionCode());
        if(stepAction == null )
            throw  new ServiceException(1001,"动作不能为空");
        if( (stepAction == EnumRuleStepAction.ADDCUSTTAG
                || stepAction == EnumRuleStepAction.DELETECUSTTAG
                || stepAction == EnumRuleStepAction.ADDCOLLECTTAG
                || stepAction == EnumRuleStepAction.DELETECOLLECTTAG)
                && StringUtils.isEmpty(vo.getTag()))
        {
            throw new ServiceException(1001, "标签不能空");
        }
        if( stepAction == EnumRuleStepAction.CAMPAIGN && ObjectUtils.isNull(vo.getClid()))
        {
            throw new ServiceException(1001, "任务队列不能为空");
        }
        if( stepAction == EnumRuleStepAction.DISTRIBUTE)
        {

            if( vo.getCfgActivity() == null)
                throw new ServiceException(1001, "未定义分案信息");

            ActivityEditVo cfgActivity = vo.getCfgActivity();
            if( ObjectUtils.isNull(cfgActivity.getActivityid()) )
                cfgActivity.setActivityid(vo.getActivityId());
            if(ObjectUtils.isNull(cfgActivity.getDistype2() ))
                throw new ServiceException(1001, "未指定分案的分配方法");
            if(StringUtils.isEmpty(cfgActivity.getDistdaymode()))
                cfgActivity.setDistdaymode("0");
            if( cfgActivity.getDistdaymode().equals("0")
                    && ObjectUtils.isNull(cfgActivity.getBindday()))
                throw new ServiceException(1001, "未指定绑定天数");
            if( cfgActivity.getDistdaymode().equals("1")
                    && StringUtils.isEmpty(cfgActivity.getFixday()))
                throw new ServiceException(1001, "未指定到期日期");
            cfgActivityService.cfgActivityUpdate(usrId,cfgActivity);
//            CfgActivity cfgActivity1 = cfgActivityService.getById(cfgActivity.getActivityid());
//            cfgActivity1.setDistype2(cfgActivity.getDistype2());
//            cfgActivity1.setDistdaymode(cfgActivity.getDistdaymode());
//            cfgActivity1.setBindday(cfgActivity.getBindday());
//            cfgActivity1.setAftermonth(cfgActivity.getAftermonth());
//            cfgActivity1.setFixday(cfgActivity.getFixday());
//           // cfgActivity1.setDisablelastgrp(cfgActivity.getDisablelastgrp());
//            cfgActivity1.setName(vo.getRuleStepName());
//            cfgActivity1.setMddt(new Date());
//            cfgActivity1.setMdusr(usrId);
//            cfgActivityService.updateById(cfgActivity1);
        }
        if( stepAction == EnumRuleStepAction.ASSIGN)
        {
            if( vo.getCfgAssignset() == null)
                throw new ServiceException(1001, "未定义派工信息");

            AssSetEditVo cfgAssignset = vo.getCfgAssignset();
            if( ObjectUtils.isNull(cfgAssignset.getAssignId()) )
                cfgAssignset.setAssignId(vo.getAssignId());
            //CfgAssignset cfgAssignset = new CfgAssignset();
            //BeanUtils.copyProperties(vo.getCfgAssignset(),cfgAssignset);
            if(ObjectUtils.isNull(cfgAssignset.getMode()))
                throw new ServiceException(1001, "未指定派工方法");
            if(StringUtils.isEmpty(cfgAssignset.getGrpid()))
                throw new ServiceException(1001, "未指定派工部门");
//            cfgAssignset.setMddt(new Date());
//            cfgAssignset.setMdusr(usrId);
//            cfgAssignsetService.save(cfgAssignset);
            cfgAssignsetService.assignSetUpdate(usrId, vo.getCfgAssignset());
        }
        //更新条件。
        insertRuleStepConditions(usrId, vo.getRuleStepId(), vo.getCfgRuleConditionsList());
        cfgRuleTaskSteps.setFilterType(vo.getFilterType());
        cfgRuleTaskSteps.setFilterFormula(vo.getFilterFormula());
        if( ObjectUtils.isNotNull(cfgRuleTaskSteps.getFilterType()) && cfgRuleTaskSteps.getFilterType() == 2)
            cfgRuleTaskSteps.setFilterSql(vo.getFilterSql());
        else
            cfgRuleTaskSteps.setFilterSql(
                    getStepConditionSql(cfgRuleTaskSteps.getRuleStepId(),cfgRuleTaskSteps.getFilterFormula()));

        cfgRuleTaskSteps.setMddt(new Date());
        cfgRuleTaskSteps.setMdusr(usrId);
        //更新策略表。
        updateById(cfgRuleTaskSteps);
        return  new CmdResVo(1);
    }
    /**
     * 删除策略。
     */
    @Override
    public CmdResVo deleteRuleStep( Long ruleStepId )
    {
        cfgRuleConditionsService.remove(new LambdaQueryWrapper<CfgRuleConditions>()
                .eq(CfgRuleConditions::getRuleStepId,ruleStepId));
        removeById(ruleStepId);
        return  new CmdResVo(1);
    }

    /**
     * 增加条件。
     */
    @Override
    public CmdResVo addRuleCondition(String usrId,  Long ruleStepId, CfgRuleConditions cfgRuleConditions)
    {
        if(ObjectUtils.isNull(cfgRuleConditions.getVarId()))
            throw new ServiceException(1001,"参数不能为空");
        if(ObjectUtils.isNull(cfgRuleConditions.getOp()))
            throw new ServiceException(1001,"方法不能为空");
        CfgRuleTaskSteps cfgRuleTaskSteps = getById(ruleStepId);
        if( cfgRuleTaskSteps == null)
            throw new ServiceException(1001,"策略不存在");
        CfgRuleVars cfgRuleVars = cfgRuleVarsService.getById(cfgRuleConditions.getVarId());
        if(cfgRuleVars.getFieldType().equals("date"))
            cfgRuleVars.setFieldType("string");
        String opSql = EnumRuleVarsOp.getOpSqlByCode(cfgRuleConditions.getOp(),cfgRuleVars,cfgRuleConditions.getOpVal());
        cfgRuleConditions.setConditionSql(opSql);
        cfgRuleConditions.setRuleStepId(ruleStepId);
        cfgRuleConditions.setInputType(cfgRuleVars.getInputType());
        cfgRuleConditionsService.save(cfgRuleConditions);
        cfgRuleTaskSteps.setMddt(new Date());
        cfgRuleTaskSteps.setMdusr(usrId);
        updateById(cfgRuleTaskSteps);
        return new CmdResVo(1,cfgRuleConditions.getConditionId().toString());
    }

    /**
     * 更新条件。
     */
    @Override
    public CmdResVo updateRuleCondition(String usrId, CfgRuleConditions cfgRuleConditions)
    {
        if(ObjectUtils.isNull(cfgRuleConditions.getVarId()))
            throw new ServiceException(1001,"参数不能为空");
        if(ObjectUtils.isNull(cfgRuleConditions.getOp()))
            throw new ServiceException(1001,"方法不能为空");
        CfgRuleTaskSteps cfgRuleTaskSteps = getById(cfgRuleConditions.getRuleStepId());
        if( cfgRuleTaskSteps == null)
            throw new ServiceException(1001,"策略不存在");
        CfgRuleVars cfgRuleVars = cfgRuleVarsService.getById(cfgRuleConditions.getVarId());
        if(cfgRuleVars.getFieldType().equals("date"))
            cfgRuleVars.setFieldType("string");
        String opSql = EnumRuleVarsOp.getOpSqlByCode(cfgRuleConditions.getOp(),cfgRuleVars,cfgRuleConditions.getOpVal());
        cfgRuleConditions.setConditionSql(opSql);
        cfgRuleConditions.setInputType(cfgRuleVars.getInputType());
        cfgRuleConditionsService.updateById(cfgRuleConditions);
        cfgRuleTaskSteps.setMddt(new Date());
        cfgRuleTaskSteps.setMdusr(usrId);
        cfgRuleTaskSteps.setFilterSql(getStepConditionSql(cfgRuleTaskSteps.getRuleStepId(),cfgRuleTaskSteps.getFilterFormula()));
        updateById(cfgRuleTaskSteps);
        return new CmdResVo(1);
    }
    /**
     * 删除条件。
     */
    @Override
    public CmdResVo deleteRuleCondition(String usrId, Long ruleConditionId )
    {

        CfgRuleConditions cfgRuleConditions = cfgRuleConditionsService.getById(ruleConditionId);
        if( cfgRuleConditions == null)
            throw new ServiceException(1001,"当前筛选条件不存在");
        cfgRuleConditionsService.removeById(ruleConditionId);
        CfgRuleTaskSteps cfgRuleTaskSteps = getById(cfgRuleConditions.getRuleStepId());
        cfgRuleTaskSteps.setMddt(new Date());
        cfgRuleTaskSteps.setMdusr(usrId);
        cfgRuleTaskSteps.setFilterSql(getStepConditionSql(cfgRuleTaskSteps.getRuleStepId(),cfgRuleTaskSteps.getFilterFormula()));
        updateById(cfgRuleTaskSteps);
        return new CmdResVo(1);
    }
    private String getStepConditionSql(Long ruleStepId,String sqlFormula)
    {
        List<CfgRuleConditions> cfgRuleConditionsList = cfgRuleConditionsService.getBaseMapper().selectList(
                new LambdaQueryWrapper<CfgRuleConditions>().eq(CfgRuleConditions::getRuleStepId,ruleStepId));
        String retSql = sqlFormula;
        for(CfgRuleConditions cfgRuleConditions : cfgRuleConditionsList){
            retSql  = retSql.replace( cfgRuleConditions.getConditionCode(), cfgRuleConditions.getConditionSql());
        }
        return retSql;
    }

    /**
     * 检查SQL 问是否正确
     * @param ruleStepId
     * @return
     */
    @Override
    public CmdResVo checkRuleStep(Long ruleStepId)
    {
        //检查是否有案件表。
        CfgRuleTaskSteps cfgRuleTaskSteps = getById(ruleStepId);
        if(cfgRuleTaskSteps == null)
            throw new ServiceException(1001,"当前策略不存在");
        if(StringUtils.isEmpty(cfgRuleTaskSteps.getFilterSql()))
            throw new ServiceException(1001,"当前策略不存在");
        try {
            conCustomerService.checkConditionSql(cfgRuleTaskSteps.getFilterSql());
        }catch (Exception ex)
        {
            return new CmdResVo(0,ex.toString());
        }
        return new CmdResVo(1,"检查OK");
    }

    @Override
    public CmdResVo runRuleStep(String usrId, Long ruleStepId,Integer isForce)
    {
        //检查是否有案件表。
        CfgRuleTaskSteps cfgRuleTaskSteps = getById(ruleStepId);
        if(cfgRuleTaskSteps == null)
            throw new ServiceException(1001,"当前策略不存在");
        if(cfgRuleTaskSteps.getStatus() != 1 && isForce != 1)
            throw new ServiceException(1001,"当前策略无效");

        return runRuleStep(usrId, cfgRuleTaskSteps);
    }

    @Override
    public CmdResVo runRuleStep(String usrId, CfgRuleTaskSteps cfgRuleTaskSteps)
    {
        EnumRuleStepAction stepAction = EnumRuleStepAction.getEnumByCode(cfgRuleTaskSteps.getActionCode());

        if(stepAction == null )
            return new CmdResVo(0,"没有设置策略执行方法");
        Calendar calendar = Calendar.getInstance();
        Date now = calendar.getTime();
        calendar.add(Calendar.DATE,-1);
        Date yesterday = calendar.getTime();
        log.info("rule step: id:<{}>, now:<{}>,startdate:<{}>, enddate:<{}>",cfgRuleTaskSteps.getRuleStepId(),
                now,cfgRuleTaskSteps.getStartDate(),cfgRuleTaskSteps.getEndDate());

        if( ObjectUtils.isNotNull(cfgRuleTaskSteps.getStartDate()) && cfgRuleTaskSteps.getStartDate().after(now))
        {
            return new CmdResVo(0,"该策略未开始");
        }
        if( ObjectUtils.isNotNull(cfgRuleTaskSteps.getEndDate()) && cfgRuleTaskSteps.getEndDate().before(yesterday))
        {
            return new CmdResVo(0,"该策略已关闭");
        }
        switch(stepAction)
        {
            case  DISTRIBUTE:
                return distribute(usrId, cfgRuleTaskSteps);
            case ASSIGN:
                return assign(cfgRuleTaskSteps);
            case CAMPAIGN:
                return campaign(cfgRuleTaskSteps);
            case ADDCUSTTAG:
                return addCustomerGrpTag(cfgRuleTaskSteps);
            case DELETECUSTTAG:
                return removeCustomerGrpTag(cfgRuleTaskSteps);
            case ADDCOLLECTTAG:
                return addCollectGrpTag(cfgRuleTaskSteps);
            case DELETECOLLECTTAG:
                return removeCollectGrpTag(cfgRuleTaskSteps);
            case AIQM:
                return autoAiQm(cfgRuleTaskSteps);
            case CCARD:
                return addCardScore(cfgRuleTaskSteps);
             default:
                return  new CmdResVo(0,"暂不支持该方法");
        }
        //return new CmdResVo(1,"策略执行完成");
    }

    /**
     *  分案
     * @param runRuleStep
     */
    private CmdResVo distribute(String usrId, CfgRuleTaskSteps runRuleStep)
    {
        // 队列：0：未逾期，1：待分案，2：在催，3：停催，4：出崔。 字段 ccc
        // 状态：  New("未分案",0),Distribute("已分案",1),Assign("已分配",2),Recycle("已回收",3),
        //    Return("已退回",4),Finish("已结案",9);

        //检查是否存在activityid
        if(ObjectUtils.isNull(runRuleStep.getActivityId()))
        //增加日志描述
            return new CmdResVo(0,"没有定义分案规则");
        CfgActivity cfgActivity = cfgActivityService.getById(runRuleStep.getActivityId());
        if(cfgActivity == null)
            return new CmdResVo(0,"没有定义分案规则"); ;
        String sql = getExcludeBlackSql(runRuleStep);
        return cfgActivityService.distribute(usrId,runRuleStep,cfgActivity,sql);

    }

    /**
     * 分工
     * @param runRuleStep
     */
    private CmdResVo assign(CfgRuleTaskSteps runRuleStep)
    {
        if(ObjectUtils.isNull(runRuleStep.getAssignId()))
            //增加日志描述
            return new CmdResVo(0,"没有定义派工规则");
        CfgAssignset cfgAssignset = cfgAssignsetService.getById(runRuleStep.getAssignId());
        if(cfgAssignset == null)
            return new CmdResVo(0,"没有定义派工规则"); ;
        String sql = getExcludeBlackSql(runRuleStep);
        return cfgAssignsetService.autoAssign(runRuleStep,cfgAssignset, sql);
    }

    /**
     *  增加客户分组
     * @param runRuleStep
     */
    private CmdResVo addCustomerGrpTag(CfgRuleTaskSteps runRuleStep)
    {
        String sql = getExcludeBlackSql(runRuleStep);
        return conCustomerService.addCustomerGrpTag(runRuleStep,sql);
    }

    /**
     * 删除客户分组
     * @param runRuleStep
     * @return
     */
    private CmdResVo removeCustomerGrpTag(CfgRuleTaskSteps runRuleStep)
    {
        String sql = getExcludeBlackSql(runRuleStep);
        return  conCustomerService.removeCustomerGrpTag(runRuleStep,sql);
    }

    /**
     *  增加客户分组
     * @param runRuleStep
     */
    private CmdResVo addCollectGrpTag(CfgRuleTaskSteps runRuleStep)
    {
        String sql = getExcludeBlackSql(runRuleStep);
        return fiCreditcasesService.addCollectGrpTag(runRuleStep,sql);
    }

    /**
     * 删除客户分组
     * @param runRuleStep
     * @return
     */
    private CmdResVo removeCollectGrpTag(CfgRuleTaskSteps runRuleStep)
    {
        String sql = getExcludeBlackSql(runRuleStep);
        return  fiCreditcasesService.removeCollectGrpTag(runRuleStep,sql);
    }

    /**
     * 派发任务
     * @param runRuleStep
     */
    private CmdResVo campaign(CfgRuleTaskSteps runRuleStep)
    {

        if( StringUtils.isEmpty(runRuleStep.getClid()))
            return new CmdResVo(0, "任务队列未设置");
//        String sql = runRuleStep.getFilterSql();
//        if(StringUtils.isEmpty(sql))
//            sql = " 1=1 ";
//        //客户黑名单。
//        if( runRuleStep.getExcludeBlack() == 1)
//            sql += " and not exists (select 1 from con_blacklist cbl where cbl.customernumber = cu.customernumber and cbl.type = 1 )";
//
//        if( runRuleStep.getExcludeWhite() == 1)
//            sql += " and not exists ( select 1 from con_blacklist cbl where cbl.customernumber = cu.customernumber and cbl.type = 2 )";
//
//        if( runRuleStep.getExcludeStop() == 1)
//            //sql += " and fi_hasstopcall(fc.creditcaseid,'CASE')=0 ";
//            sql += "  and  not exists( SELECT 1  \n" +
//                    "    FROM fi_stopcall s  \n" +
//                    "    WHERE s.stopkey = fc.creditcaseid and s.stoptype = 'CASE' AND s.status = 2 )";
//        if(runRuleStep.getExcludeCustomerStop() == 1)
//            //sql += " and fi_hasstopcall(cu.customernumber,'CUSTOMER')=0 ";
//            sql += "  and  not exists( SELECT 1  \n" +
//                    "    FROM fi_stopcall s  \n" +
//                    "    WHERE s.stopkey = cu.customernumber and s.stoptype = 'CUSTOMER' AND s.status = 2 )";

        String sql = getExcludeBlackSql(runRuleStep);
        return  fiTaskService.autoCreateTaskList(runRuleStep,sql);
    }

    private  CmdResVo autoAiQm(CfgRuleTaskSteps runRuleStep)
    {
        if( ObjectUtils.isNull(runRuleStep.getQmTemplateId()))
            return new CmdResVo(0, "智能质检模板未设置");

//        String sql = runRuleStep.getFilterSql();
//        if(StringUtils.isEmpty(sql))
//            sql = " 1=1 ";
//        //客户黑名单。
//        if( runRuleStep.getExcludeBlack() == 1)
//            sql += " and not exists (select 1 from con_blacklist cbl where cbl.customernumber = cu.customernumber and cbl.type = 1 )";
//
//        if( runRuleStep.getExcludeWhite() == 1)
//            sql += " and not exists ( select 1 from con_blacklist cbl where cbl.customernumber = cu.customernumber and cbl.type = 2 )";
//
//        if( runRuleStep.getExcludeStop() == 1)
//            //sql += " and fi_hasstopcall(fc.creditcaseid,'CASE')=0 ";
//            sql += "  and  not exists( SELECT 1  \n" +
//                    "    FROM fi_stopcall s  \n" +
//                    "    WHERE s.stopkey = fc.creditcaseid and s.stoptype = 'CASE' AND s.status = 2 )";
//        if(runRuleStep.getExcludeCustomerStop() == 1)
//            //sql += " and fi_hasstopcall(cu.customernumber,'CUSTOMER')=0 ";
//            sql += "  and  not exists( SELECT 1  \n" +
//                    "    FROM fi_stopcall s  \n" +
//                    "    WHERE s.stopkey = cu.customernumber and s.stoptype = 'CUSTOMER' AND s.status = 2 )";

        String sql = getExcludeBlackSql(runRuleStep);

        return  qmDataService.autoAiQm(runRuleStep,sql);

    }
    private  CmdResVo addCardScore(CfgRuleTaskSteps runRuleStep)
    {
        String sql = getExcludeBlackSql(runRuleStep);
        conCustomerService.addCardScore(runRuleStep,sql);
        return new CmdResVo(1);
    }
    @Override
    public String getExcludeBlackSql(CfgRuleTaskSteps cfgRuleTaskSteps)
    {
        String sql = cfgRuleTaskSteps.getFilterSql();
        if( StringUtils.isEmpty(sql))
            sql = " 1=1 ";
        //客户黑名单。
        if( cfgRuleTaskSteps.getExcludeBlack() == 1)
            sql += " and not exists (select 1 from con_blacklist cbl where cbl.customernumber = cu.customernumber and cbl.type = 1 )";

        if( cfgRuleTaskSteps.getExcludeWhite() == 1)
            sql += " and not exists ( select 1 from con_blacklist cbl where cbl.customernumber = cu.customernumber and cbl.type = 2 )";

        if( cfgRuleTaskSteps.getExcludeStop() == 1)
            //sql += " and fi_hasstopcall(fc.creditcaseid,'CASE')=0 ";
            sql += "  and  not exists( SELECT 1  \n" +
                    "    FROM fi_stopcall s  \n" +
                    "    WHERE s.stopkey = concat('',fc.creditcaseid) and s.stoptype = 'CASE' AND s.status = 2 )";
        if(cfgRuleTaskSteps.getExcludeCustomerStop() == 1)
            //sql += " and fi_hasstopcall(cu.customernumber,'CUSTOMER')=0 ";
            sql += "  and  not exists( SELECT 1  \n" +
                    "    FROM fi_stopcall s  \n" +
                    "    WHERE s.stopkey = cu.customernumber and s.stoptype = 'CUSTOMER' AND s.status = 2 )";

        return sql;
    }


}




